import 'dart:convert';

import 'package:rxdart/rxdart.dart';
import 'package:web_socket_channel/io.dart';
// import 'package:web_socket_channel/web_socket_channel.dart';
// import 'package:web_socket_channel/status.dart' as status;

class DemoModel {
  ///
  final BehaviorSubject<int> _subject = BehaviorSubject.seeded(0);
  final BehaviorSubject<int> _subjectDemo = BehaviorSubject.seeded(1);

  late IOWebSocketChannel channel;

  get streamDemo => _subjectDemo.stream;
  get streamValue => _subjectDemo.value;

  get stream => _subject.stream;
  get value => _subject.value;

  increment() {
    _subject.add(value + 1);
  }

  decrement() {
    _subject.add(value - 1);
  }

  // 连接websocket
  init() {
    // final wsUrl = Uri.parse('ws://192.168.0.108:9091/socket/get');
    channel =
        IOWebSocketChannel.connect("ws://192.168.0.108:9091/socket/get/1");
    channel.stream.listen((message) {
      print(message);
      // channel.sink.add('received!');
      // channel.sink.close(status.goingAway);
    });
  }

  send() {
    Map<String, dynamic> params = {"userId": 1, "msg": "你好哇"};
    Map<String, dynamic> data = {"userId": 1, "msg": params};
    channel.sink.add(jsonEncode(data));
    // channel.sink.close(status.goingAway);
  }
}
